package com.adcage.ojudgebackendjudgeservice.judge.codeSandbox.Impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.adcage.ojudgebackendjudgeservice.judge.codeSandbox.CodeSandbox;
import com.adcage.ojudgebackendmodel.codesandbox.ExecuteCodeRequest;
import com.adcage.ojudgebackendmodel.codesandbox.ExecuteCodeResponse;
import com.adcage.ojudgebackendmodel.common.ErrorCode;
import com.adcage.ojudgebackendmodel.exception.BusinessException;
import com.adcage.ojudgebackendmodel.utils.Logger;

/**
 * 远程调用代码沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";//TODO,先写一个假值

    /**
     * 代码沙箱服务地址
     */
    private static final String url = "http://localhost:8366/executeCode";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        System.out.println("RemoteCodeSandBox");
        String json = JSONUtil.toJsonStr(request);
        Logger.info("executeCode request:" + json);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if (StrUtil.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteSandbox error" + responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
